public class Demo1 {

    public static void main(String[] args) {
       int[][] grid = {{1, 3, 1}, {1, 5, 1}, {4, 2, 1} };
        System.out.println(maxValues(grid));
    }

    public static int maxValues(int[][] grid) {
        int k = 0;
        int r = 0;
        int p = grid[k][r];

        while (k < grid.length - 1 && r < grid[0].length - 1) {
            if (grid[k + 1][r] > grid[k][r + 1] ) {
                p += grid[k + 1][r];

                k++;
            } else if (grid[k + 1][r] < grid[k][r + 1]){
                p += grid[k][r + 1];
                r++;
            }
        }
        if (k >= grid.length - 1) {
            for (int i = (r + 1); i < grid[0].length ; i++) {
                p += grid[k][i];
            }
        } else if (r >= grid.length - 1) {
            for (int i = (k ); i < grid.length ; i++) {
                p += grid[i][r];
            }
        }
        return p;
    }
}
